<template>
  <div ref="read" v-loading="loading" class="read">
    <div
      class="read-head"
      :style="
        isDialog
          ? 'box-shadow: rgb(0 0 0 / 5%) 1px 3px 0px, rgba(0, 0, 0, 0.02) -2px 4px 0px;'
          : ''
      "
    >
      <div class="read-head-left">
        <div class="left-title">
          <span
            style="
              font-weight: 700;
              font-size: 16px;
              font-family: MicrosoftYaHei, MicrosoftYaHei-Bold, sans-serif;
              line-height: 21px;
              text-align: left;
              color: #191919;
            "
            >{{ current_content.title }}</span
          >
          <span style="margin-right: 24px; margin-left: auto">
            <span v-if="current_content_details.dept">
              {{ LANG.DEPT }}&nbsp;:&nbsp;{{ current_content_details.dept }}
            </span>
            <span>{{ current_content.createDate }}</span>
          </span>
        </div>
      </div>
      <div class="read-head-right">
        <div class="right-title">
          <i
            style="
              color: #999999;
              margin-left: 29px;
              height: 40px;
              line-height: 40px;
            "
            class="fks-icon-view"
          />
          <span
            style="
              height: 40px;
              margin-right: 5px;
              margin-left: 5px;
              line-height: 40px;
            "
          >
            {{ current_content.hits }}
          </span>

          <fks-button
            v-show="pre_view_file_control"
            :style="
              isDialog
                ? 'margin-left: auto; margin-right: 16px'
                : 'margin-left: auto'
            "
            @click="backToContent"
          >
            <i class="fks-reject" style="margin-right: 8px" />
            {{ LANG.BACK_TO_CONTENT }}
          </fks-button>
          <fks-button
            v-show="!pre_view_file_control"
            v-if="edit_flag"
            v-permission="['content:edit']"
            :style="
              isDialog
                ? 'margin-left: auto; margin-right: 16px'
                : 'margin-left: auto'
            "
            icon="fks-icon-edit"
            @click="openEditor"
          >
            {{ LANG.GOTO_EDIT_PAGE }}
          </fks-button>
        </div>
      </div>
    </div>
    <div
      id="read-body"
      class="read-body"
      :style="isDialog ? ' margin-bottom:0px;' : ''"
    >
      <!-- 正文 -->
      <div
        style="
          width: 100%;
          height: calc(100% - 140px) !important;
          overflow-y: scroll;
        "
        :style="
          showFiles.length
            ? 'height: calc(100% - 140px) !important;'
            : 'height: calc(100%) !important;'
        "
      >
        <article v-show="!pre_view_file_control" class="article-text">
          <div class="article-container">
            <div class="article-text-title">
              {{ current_content.title }}
            </div>
            <div
              v-if="
                findFieldByName('TITLE2') &&
                findFieldByName('TITLE2').fieldValue != '' &&
                findFieldByName('TITLE2').fieldValue
              "
              class="article-text-title2"
            >
              ——{{ findFieldByName('TITLE2').fieldValue }}
            </div>
            <div
              v-if="
                findFieldByName('TITLE3') &&
                findFieldByName('TITLE3').fieldValue != '' &&
                findFieldByName('TITLE3').fieldValue
              "
              class="article-text-title3"
            >
              {{ findFieldByName('TITLE3').fieldValue }}
            </div>
            <div
              v-if="
                findFieldByName('AUTHORUSERFULLNAME') &&
                findFieldByName('AUTHORUSERFULLNAME').fieldValue != '' &&
                findFieldByName('AUTHORUSERFULLNAME').fieldValue
              "
              class="article-text-author"
            >
              {{ LANG.AUTHOR }}：{{
                findFieldByName('AUTHORUSERFULLNAME').fieldValue
              }}
            </div>
            <div
              v-if="
                findFieldByName('ABSTRACT') &&
                findFieldByName('ABSTRACT').fieldValue != '' &&
                findFieldByName('ABSTRACT').fieldValue
              "
              class="article-text-abstract"
            >
              {{ LANG.ABSTRACT }}：{{ findFieldByName('ABSTRACT').fieldValue }}
            </div>
            <div
              v-show="!pre_view_file_control"
              id="ARTICLE"
              ref="ARTICLE"
              class="article-text-content"
              name="ARTICLE"
              v-html="current_content.context"
            />
            <div
              v-if="current_content_details.inputer"
              class="article-text-inputer"
            >
              {{ LANG.COPYREADER }}：{{ current_content_details.inputer }}
            </div>
          </div>
        </article>
        <!--     附件预览    -->
        <article
          v-show="pre_view_file_control"
          class="article-text"
          style="height: 100% !important; padding-top: 0"
        >
          <div
            v-show="pre_view_file_control"
            class="article-container"
            style="height: 100%; overflow: hidden"
          >
            <pre-view v-if="pre_view_file_control" :file-token="current_file" />
          </div>
        </article>
      </div>

      <div
        v-if="showFiles.length"
        style="
          position: absolute;
          bottom: 0;
          width: 100%;
          height: 100px !important;
          border-top: 1px solid #eee;
          overflow-y: scroll;
        "
      >
        <!-- 附件 -->
        <section class="file">
          <div v-show="showFiles.length">
            <div class="file-list" style="width: 1200px; margin-top: 16px">
              <div
                v-for="(file, index) in showFiles"
                :key="`file_${index}`"
                class="file-list-item"
              >
                <div class="file-img">
                  <fks-icon :icon-class="getFileIconByExtName(file.extName)" />
                </div>
                <div class="file-describe" @click="preViewFile(file)">
                  <span>
                    {{ file.fileName }}
                  </span>
                  <span style="margin-left: 8px">
                    ({{ (Number(file.size) / 1024).toFixed(2) + ' KB' }})
                  </span>
                </div>
                <div class="file-operate">
                  <div v-if="downloadFlag" @click="download(file)">
                    <i class="fks-icon-download" />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>
      </div>
    </div>
  </div>
</template>

<script>
import { updateContentHit } from './api/index'
import {
  getContentById,
  findFieldByName,
  getContentDetail,
  getContentStatus
} from '@/modules/Content/api'
import { getFile, downloadFile } from '@/api/file'
import { getFileIconByExtName } from '@/utils/file'
import { getRevisionContent, getRevisionContentDetail } from './api/index'
import PreView from '@/components/PreView/index'
import { download } from '@/utils/file'
import mix from '@/mixins/module'
import * as actionTypes from '@/store/Action/actionTypes'
import { VISITED_VIEWS } from '@/store/State/stateTypes'
export default {
  name: 'Read',
  components: { PreView },
  mixins: [mix],
  props: {
    id: String,
    isDialog: {
      type: Boolean,
      default: false
    },
    isRevision: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      hasFile: true,
      contentStatus: 'PUBLISH',
      current_content: {},
      current_content_details: [],
      fileList: [],
      showFiles: [], //fileList过滤之后的文件
      show_setting: true,
      edit_flag: false,
      isEdit: false,
      downloadFlag: true,
      pre_view_file_control: false,
      loading: true,
      current_file: ''
    }
  },
  computed: {
    visitedViews() {
      return this.$store.state[VISITED_VIEWS]
    },
    contentId() {
      if (this.id) {
        return this.id
      }
      return this.$route.params.id
    }
  },
  watch: {
    contentId(val) {
      if (val) {
        this.initData()
      }
    }
  },
  created() {
    this.initData()
  },
  mounted() {
    document.documentElement.addEventListener('click', this.blurInput)
    window.addEventListener('resize', this.resize)
  },
  beforeDestroy() {
    // localStorage.removeItem('CURRENT_content')
    document.documentElement.removeEventListener('click', this.blurInput)
    window.removeEventListener('resize', this.resize)
  },
  methods: {
    quit() {
      setTimeout(() => {
        this.loading = false
        this.closeSelectedTag()
        this.$router.push({
          name: 'contentList'
        })
      }, 500)
    },

    /**
     * @description:提交/暂存后删除标签
     */
    closeSelectedTag() {
      for (let i = 0; i < this.visitedViews.length; i++) {
        if (this.visitedViews[i].activePath == this.$route.path) {
          this.$store.dispatch(actionTypes.DEL_VIEW, this.visitedViews[i])
          break
        }
      }
    },

    getFileIconByExtName(extName) {
      return getFileIconByExtName(extName)
    },

    /**
     * @description: 进入编辑
     */
    openEditor() {
      this.$router.push({
        name: 'edit',
        query: {
          ContentId: this.contentId
        }
      })
    },

    /**
     * @description: 根据name获取可变字段
     */
    findFieldByName(name) {
      return findFieldByName(name, this.current_content_details)
    },

    /**
     * @description: 更新点击量
     */
    updateContentHit(content) {
      updateContentHit(content)
    },

    /**
     * @description: 内容获取的入口方法
     */
    getContent() {
      let id = this.contentId
      if (this.isRevision) {
        getRevisionContent(id)
          .then((res) => {
            if (res.status) {
              let content = res.data
              this.current_content = content
              this.getRevisionContentDetail(id)
            }
          })
          .catch(() => {})
      } else {
        getContentById(id)
          .then((res) => {
            if (res.status && res.data) {
              let content = res.data
              this.current_content = content
              //更新点击次数
              if (content.hits) {
                content.hits = Number(content.hits) + 1
              } else {
                content.hits = 1
              }
              this.current_content.hits = content.hits
              this.updateContentHit(content)
            } else {
              // this.quit()
            }
          })
          .catch(() => {})
        this.getStatus(id)
        this.getDetailListById(id)
      }
    },

    /**
     * @description: 获取内容的Status
     */
    getStatus(id) {
      getContentStatus(id)
        .then((res) => {
          if (res.status && res.data) {
            this.contentStatus = res.data
            this.edit_flag =
              res.data == 'DRAFT' ||
              res.data == 'FAILURE' ||
              res.data == 'REVOKE'
                ? true
                : false
          } else {
            this.quit()
          }
        })
        .catch(() => {})
    },

    /**
     * @description: 根据内容id获得它的详情列表
     */
    getDetailListById(contentId) {
      let temp = {
        contentId: contentId,
        page: 1,
        size: 150
      }
      getContentDetail(temp)
        .then((res) => {
          if (res.status && res.data) {
            this.current_content_details = res.data
            this.drawDetails()
          } else {
            // this.quit()
          }
        })
        .catch(() => {})
    },

    /**
     * @description: 根据历史版本id获得它的详情列表
     */
    getRevisionContentDetail(contentId) {
      getRevisionContentDetail(contentId)
        .then((res) => {
          if (res.status) {
            this.current_content_details = res.data
            this.drawDetails()
          }
        })
        .catch(() => {})
    },

    //针对模板处理
    drawDetails() {
      this.hasFile = false
      let field = this.findFieldByName('FILE')
      if (field) this.getFileList()
      else {
        this.loading = false
      }

      field = this.findFieldByName('FILEDOWNFLAG')
      if (!field) this.downloadFlag = true
      else this.downloadFlag = Number(field.fieldValue)

      field = this.findFieldByName('DEPTNAME')
      if (field) {
        this.current_content_details.dept = JSON.parse(
          field.fieldValue
        ).createDept
      }

      field = this.findFieldByName('INPUTERFULLNAME')
      if (field) {
        this.current_content_details.inputer = JSON.parse(
          field.fieldValue
        ).createFullname
      }
    },

    /**
     * @description: 附件获取
     */
    getFileList() {
      let field = this.findFieldByName('FILE')
      let g9s = [field.fieldValue]
      g9s = g9s.filter((val) => {
        return val != ''
      })
      if (g9s.length) {
        getFile({ g9s: g9s })
          .then((res) => {
            if (res.status) {
              try {
                this.fileList = res.data
                this.showFiles = this.filterFile()
                if (res.data.length == 0) {
                  this.loading = false
                  return
                }
                this.hasFile = true
                //如果正文没有内容，打开第一个附件
                if (
                  !this.current_content.context &&
                  res.data &&
                  res.data.length
                ) {
                  this.$message.info(this.LANG.TIP_NO_CONTENT)
                  setTimeout(() => {
                    this.preViewFile(res.data[0])
                  }, 500)
                }
              } catch (e) {
                this.$message({
                  type: 'error',
                  message: '系统异常！'
                })
              }
            }
            this.loading = false
          })
          .catch(() => {
            this.$message.error(this.LANG.ERROR_GET_FILE)
            this.loading = false
          })
      } else {
        this.loading = false
      }
    },
    filterFile(flag) {
      let file = []
      if (flag) {
        file = this.fileList.filter((val) => {
          return val.groupToken == flag
        })
      } else {
        file = [...this.fileList]
      }
      return file
    },

    /**
     * @description: 附件下载和预览的响应
     */
    download(file) {
      downloadFile(file.fileToken)
        .then((res) => {
          download(file, res.data)
        })
        .catch(() => {})
    },

    preViewFile(file) {
      this.$set(this, 'pre_view_file_control', true)
      this.$set(this, 'current_file', file.fileToken)
    },
    backToContent() {
      this.$set(this, 'pre_view_file_control', false)
    },

    /**
     * @description: 初始化
     */
    clearData() {
      this.loading = true
      this.downloadFlag = true
      this.edit_flag = false
      this.current_content = {}
      this.current_content_details = []
      this.fileList = []
      this.showFiles = []
      this.backToContent()
    },
    initData() {
      this.clearData()
      this.getContent()
    }
  }
}
</script>

<style scoped lang="scss">
@import 'asset/style/read';
</style>